package com.guet.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.guet.domain.SeckillVoucher;
import com.guet.domain.VoucherOrder;
import com.guet.mapper.VoucherOrderMapper;
import com.guet.service.SeckillVoucherService;
import com.guet.service.VoucherOrderService;
import com.guet.utils.RedisID;
import com.guet.utils.Result;
import com.guet.utils.SimpleRedisLock;
import com.guet.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class VoucherOrderServiceImpl implements VoucherOrderService {

    @Resource
    private VoucherOrderMapper voucherOrderMapper;
    @Resource
    private SeckillVoucherService seckillVoucherService;
    @Resource
    private RedisID redisID;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    private VoucherOrderService proxy;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";
        @Override
        public void run() {
            while(true){
                try {
                    // 获取stream.orders消息队列中的订单信息
                    // XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    // 没有取到消息,继续下一次循环
                    if(list == null || list.isEmpty()){
                        continue;
                    }
                    // 解析消息
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder order = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    // 创建订单
                    proxy.createVoucherOrder(order);
                    // ACK确认 XACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while(true){
                try{
                    // 获取pending-list中的订单信息
                    // XREADGROUP GROUP g1 c1 COUNT 1 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    // pending-list中没有异常消息,结束循环
                    if(list == null || list.isEmpty()){
                        break;
                    }
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder order = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
                    proxy.createVoucherOrder(order);
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch(Exception e){
                    log.error("处理pending-list订单异常",e);
                    try{
                        Thread.sleep(20);
                    } catch(InterruptedException ex){
                        ex.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public Result seckillVoucher(Long id) {
        SeckillVoucher voucher = seckillVoucherService.getById(id);
        if(voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀还未开始");
        }
        if(voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        if(voucher.getStock() < 1){
            return Result.fail("库存不足");
        }

        Long userId = UserHolder.getUser().getId();
        long orderId = redisID.nextId("order");
        // 执行lua脚本(库存是否充足,是否已下过单,原子性)
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                id.toString(),userId.toString(),String.valueOf(orderId)
        );
        long r = result.longValue();
        if(r != 0) {
            return Result.fail(r == 1 ? "库存不足":"不能重复下单");
        }
        proxy = (VoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }

    @Transactional
    public void createVoucherOrder(VoucherOrder order) {
        Long voucherId = order.getVoucherId();
        boolean success = seckillVoucherService.updateStock(1,voucherId);
        if(!success){
            log.error("库存不足");
            return;
        }
        order.setPayType(1);
        order.setStatus(1);
        voucherOrderMapper.save(order);
    }
}
